package com.windbell.pick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.windbell.util.HttpUtils;

@Repository()
public class CsdnTop10 extends BasePicker {

	public static String ListError = "列表分隔符异常";

	public static void main(String[] args) {
		BasePicker picker = new CsdnTop10();
		// List<Map> maps =picker.list();
		// System.out.println(picker.list());

		Map map = new HashMap();
		map.put(AURL, "http://bbs.csdn.net/topics/390529625");
		map.put(ATITLE, "程序员租房的故事");
		Map m = picker.context(map);
		List body = (List) m.get(Body);
		for (int i = 0; i < body.size(); i++) {
			System.out.println(i + "楼" + body.get(i));
		}
	}

	@Override
	public List<Map> list() {
		List<Map> maps = new ArrayList();
		try {
			String result = HttpUtils.get2str("http://www.csdn.net",
					CHARSET_UTF);
			// 1.列表内容
			String listStr = limit(result, "程序人生</a>", "</ul>");
			// 2.分割列表
			List<String> list = limitsByTag(listStr, "a");
			// 3.解析A的titile和url
			for (String a : list) {
				maps.add(parseA(a));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return maps;
	}

	@Override
	public Map context(Map map) {
		Map result = new HashMap(map);
		try {
			String resultStr = HttpUtils.get2str(map.get(AURL) + "",
					CHARSET_UTF);
			// 1.title
			String titleStr = limit(resultStr, "class=\"detail_title\">",
					"</h1>");
			titleStr = limitByTag(titleStr, "h1");
			result.put(TITLE, titleStr);
			// 2.bodys
			String contextStr = subString(resultStr,
					"<div class=\"detailed\">", 0);
			List<String> list = limitsByTag(contextStr, "table");

			Object bodys = result.get(Body);
			if (bodys != null) {
				List body = (List) bodys;
				result.put(Body, body.addAll(list));
			} else {
				result.put(Body, list);
			}
			// 3.next page
			int next = resultStr.indexOf("class=\"next\">下一页</a>");
			if (next > -1) {
				String nextStr = resultStr.substring(
						resultStr.lastIndexOf("<a", next), next + 23);
				String url = parseA(nextStr).get(AURL).toString();
				url = "http://bbs.csdn.net" + url;
				result.put(AURL, url);
				context(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
